package com.example.yiqinmanagersystem.httpapi;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

/*
 **@Author:youpeng
 **Created on 2022/9/12
 */
@Component
public class HttpUtils {

    public String getData() throws Exception{
        //1.请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();

        CloseableHttpClient httpClient = null;
        HttpGet request = null;
        CloseableHttpResponse response = null;

        /*
        * 网易爬虫:  http://c.m.163.com/ug/api/wuhan/app/data/list-total
        * 腾讯爬虫： https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5
        * */

        try {
            //2.创建httpClient
            httpClient = HttpClients.createDefault();
            //3.发送网络请求
            request = new HttpGet("http://c.m.163.com/ug/api/wuhan/app/data/list-total");
            //4.配置信息
            request.setConfig(requestConfig);
            //5.发送网络请求
            response = httpClient.execute(request);
            //6.状态码是否成功
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                //6.解析数据
                HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity, "utf-8");
                return string;
            }
        }finally {
            if(response!=null) {
                response.close();
            }
            if(request!=null) {
                request.releaseConnection();
            }
            if(httpClient!=null){
                httpClient.close();
            }
        }
        return null;
    }
}
